package com.mark.app.chat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.ImmediateEventExecutor;

import java.net.InetSocketAddress;
  //   refer to  http://my.oschina.net/u/1756290/blog/363247
/**
 * Created by WEIBIN521 on 2016/3/7.
 */
public class ChatServer {
    private final ChannelGroup group = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);

    private final EventLoopGroup workGroup = new NioEventLoopGroup();

    private Channel channel;

    public ChannelFuture start(InetSocketAddress address){

        ServerBootstrap boot = new ServerBootstrap();
        boot.group(workGroup).channel(NioServerSocketChannel.class).childHandler(createInitializer(group));

        ChannelFuture f = boot.bind(address).syncUninterruptibly();

        channel = f.channel();

        return f;
    }

    protected ChannelHandler createInitializer(ChannelGroup group){
        return new ChatServerInitializer(group);
    }

    public void destory(){
        if(channel != null) channel.close();
        group.close();
        workGroup.shutdownGracefully();
    }

    public static void main(String[] args) {

        final ChatServer chat = new ChatServer();
        ChannelFuture f = chat.start(new InetSocketAddress(2048));
        System.out.println("ChatServer.main  ...... ");
        Runtime.getRuntime().addShutdownHook(new Thread(){
            public void run(){
                chat.destory();
            }
        });
        f.channel().closeFuture().syncUninterruptibly();

    }
}
